import { FunctionComponent, useEffect } from 'react';
import styles from './editCanvas.module.scss';
import { Spin } from 'antd';
import { getComponentByType } from './index';
import { ComponentInfoType } from '../../zustandStore/questionStore';
import { useGetComponentInfo } from '../../hooks/useGetComponentInfo';
import useBindCanvasKeyPress from '../../hooks/useBindCanvasKeyPress';
import SortableContainer from '../dragSortable/SortableContainer';
import SortableItem from '../dragSortable/sortableItem';
interface EditCanvasProps {
  loading: boolean;
}
const EditCanvas: FunctionComponent<EditCanvasProps> = (props) => {
  const { components, selectedId, changeSelectedId, moveComponent } = useGetComponentInfo();
  //处理selectid
  const hanlderChangeSelectedId = (e: React.MouseEvent, component: ComponentInfoType) => {
    console.log(component);
    //阻止冒泡
    e.stopPropagation();
    changeSelectedId(component.id);
  };
  //获取组件的方法
  const getComponent = (c: ComponentInfoType) => {
    const { Component } = getComponentByType(c.type)!;
    if (!Component) return;
    return <Component {...c.props} />;
  };
  //绑定快捷键
  useBindCanvasKeyPress();
  // 当selectid改变时，重新聚焦到标定位置，解决当插入或者修改组件时，无法使用键盘
  useEffect(() => {
    const el = document.getElementById('tag');
    el?.blur();
    el?.focus();
  }, [selectedId]);
  const hanlderDragEnd = (oldIndex: number, newIndex: number) => {
    moveComponent(oldIndex, newIndex);
  };
  return (
    <>
      {props.loading ? (
        <div style={{ textAlign: 'center', marginTop: '24px' }}>
          <Spin></Spin>
        </div>
      ) : (
        <SortableContainer items={components} onDragEnd={hanlderDragEnd}>
          <div className={styles.canvas}>
            {components
              .filter((c) => !c.isHidden)
              .map((component) => (
                <SortableItem key={component.id} id={component.id}>
                  <div
                    className={`${styles['component-wrapper']} ${component?.id === selectedId ? styles.active : ''} ${
                      component?.isLocked ? styles.locked : ''
                    }`}
                    onClick={(e) => hanlderChangeSelectedId(e, component)}>
                    <div className={styles.component} tabIndex={0}>
                      {getComponent(component)}
                    </div>
                  </div>
                </SortableItem>
              ))}
          </div>
        </SortableContainer>
      )}
    </>
  );
};

export default EditCanvas;
